package com.xjoyt.pay.controllers.seabluesky;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xjoyt.pay.dto.CallbackResult;
import com.xjoyt.pay.dto.MerchantChannelRegister;
import com.xjoyt.pay.dto.OrderUrlResult;
import com.xjoyt.pay.dto.params.CallbackParam;
import com.xjoyt.pay.dto.params.MerchantRateRegister;
import com.xjoyt.pay.dto.params.OrderAdapterParam;
import com.xjoyt.pay.util.JSONUtil;
import com.xjoyt.pay.util.TzHttpUtils;
import com.xjoyt.pay.util.TzSignUtil;
import com.xjoyt.pay.vo.Order;

/**
 * demo适配器
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping("seaBlueSky/scanCode")
public class ScanCodeController {
	private static final String url = "http://39.108.135.251/pay/XFPayOrder";// 请求上游地址

	/**
	 * 商户进件
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("register")
	public MerchantChannelRegister register(@RequestBody MerchantRateRegister param) {
		MerchantChannelRegister result = new MerchantChannelRegister();
		result.no = "300001000090003";
		result.key = "K9m9y7";
		return result;
	}

	/**
	 * 微信 向上游发起订单，前置条件订单信息已验证、订单已保存
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("wechatScan")
	public OrderUrlResult wechatScan(String no, String keys, String groupIds, String terminalCodes,
			@RequestBody OrderAdapterParam param) {
		OrderUrlResult orderUrlResult = new OrderUrlResult();

		String out_order_no = param.order.no;// 订单号 注：每次测试的订单号不能重复
		String notify_url = param.order.orderConfig.notifyUrl;// 异步通知地址
		// String return_url = "";// 同步通知地址
		// String show_url = "";// 商品展示地址
		String body = param.param.detail;// 商品描述
		String payMoney = param.order.money + "";
		String appId = no;// 商户编号,待配置
		String key = keys;// 秘钥,待配置
		String groupId = groupIds;// 商户参数，待配置
		String terminalCode = terminalCodes;// 商户参数，待配置
		String datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		try {
			Map<String, String> params = new HashMap<String, String>();
			params.put("merchantCode", appId);
			params.put("terminalCode", terminalCode);
			params.put("orderNum", out_order_no);
			params.put("payMoney", payMoney);
			params.put("productName", body);// 商品名称
			params.put("notifyUrl", notify_url);// 异步回调地址
			params.put("groupId", groupId);
			params.put("service", "SMZF004");
			params.put("signType", "MD5");
			params.put("datetime", datetime);

			String _sign = TzSignUtil.sign(params, key);
			params.put("sign", _sign);
			String bodyStr = TzSignUtil.getBodyStr(params);
			String result = TzHttpUtils.sendPost(url, bodyStr);
			Map<String, String> map = JSONUtil.jsonToMap(result);
			String pl_url = map.get("pl_url");
			if (!StringUtils.isEmpty(pl_url)) {
				orderUrlResult.success = true;
				orderUrlResult.url = map.get("pl_url");
				return orderUrlResult;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		orderUrlResult.success = false;
		return orderUrlResult;
	}

	/**
	 * 支付宝 向上游发起订单，前置条件订单信息已验证、订单已保存
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("aliScan")
	public OrderUrlResult aliScan(String no, String keys, String groupIds, String terminalCodes,
			@RequestBody OrderAdapterParam param) {
		OrderUrlResult orderUrlResult = new OrderUrlResult();
		String out_order_no = param.order.no;// 订单号 注：每次测试的订单号不能重复
		String notify_url = param.order.orderConfig.notifyUrl;// 异步通知地址
		// String return_url = param.order.orderConfig.successUrl;// 同步通知地址
		// String show_url = param.order.orderConfig.successUrl;// 商品展示地址
		String body = param.param.detail;// 商品描述
		String payMoney = param.param.money + "";
		String appId = no;// 商户编号,待配置
		String key = keys;// 秘钥,待配置
		String groupId = groupIds;// 商户参数，待配置
		String terminalCode = terminalCodes;// 商户参数，待配置
		String datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		try {
			Map<String, String> params = new HashMap<String, String>();
			params.put("merchantCode", appId);
			params.put("terminalCode", terminalCode);
			params.put("orderNum", out_order_no);
			params.put("payMoney", payMoney);
			params.put("productName", body);// 商品名称
			params.put("notifyUrl", notify_url);// 异步回调地址
			params.put("groupId", groupId);
			params.put("service", "SMZF005");
			params.put("signType", "MD5");
			params.put("datetime", datetime);

			String _sign = TzSignUtil.sign(params, key);
			params.put("sign", _sign);
			String bodyStr = TzSignUtil.getBodyStr(params);
			String result = TzHttpUtils.sendPost(url, bodyStr);
			Map<String, String> map = JSONUtil.jsonToMap(result);
			String pl_url = map.get("pl_url");
			if (!StringUtils.isEmpty(pl_url)) {
				orderUrlResult.success = true;
				orderUrlResult.url = map.get("pl_url");
				return orderUrlResult;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		orderUrlResult.success = false;
		return orderUrlResult;
	}

	/**
	 * 回调
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("callback")
	public CallbackResult callback(@RequestBody CallbackParam param) {
		CallbackResult result = new CallbackResult();
		result.success = false;
		// 上游响应
		result.callbackResponse = "FAIL";
		Map<String, String> dataMap = new HashMap<>();
		if (param.params != null) {
			for (Entry<String, String[]> entry : param.params.entrySet()) {
				if (entry.getValue() == null || entry.getValue().length <= 0) {
					continue;
				}
				dataMap.put(entry.getKey(), entry.getValue()[0]);
			}
		}
		String orderNum = dataMap.get("orderNum");// 合作商订单号
		String pl_orderNum = dataMap.get("pl_orderNum");// 平台订单号
		// 交易金额
		String pl_payState = dataMap.get("pl_payState");// 4 支付成功
		// 请求的交易服务业务码 参考左侧common板块中的业务码说明
		String pl_sign = dataMap.get("pl_sign");// 数据的签名字符。签名生成规则请参考左侧common板块中的数据签名说明
		if (StringUtils.isEmpty(orderNum) || StringUtils.isEmpty(pl_orderNum) || StringUtils.isEmpty(pl_payState)
				|| StringUtils.isEmpty(pl_sign)) {
			return result;
		}
		if (!"4".equals(pl_payState)) {
			return result;
		}
		result.success = true;
		result.tradeNo = pl_orderNum;
		result.callbackResponse = "SUCCESS";
		return result;
	}

	/**
	 * 结算状态查询
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("settlement")
	public OrderUrlResult settlement(String type, @RequestBody Order param) {
		OrderUrlResult orderUrlResult = new OrderUrlResult();
		if (!StringUtils.isEmpty(type)) {
			if (type.equals("T0")) {
				orderUrlResult.success = true;
				return orderUrlResult;
			}
		}
		orderUrlResult.success = false;
		return orderUrlResult;
	}
}
